<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
</head>

<body>
    <div><button onclick="connectToMQTT()" id="btnStart">点击开始</button></div>
  
    <div class="ctl">
        <div class="hideblind">
            <div style="width:350px;background-color:black;">
                <br>
                <div id="smeterpeak"
                    style="width: 117.3px; height: 4px; background-color: rgb(255, 128, 0); position: absolute;">
                    <div style="position:absolute;width:0px;height:0px;"></div>
                </div>
                <div id="smeterbar"
                    style="width: 117.3px; height: 4px; background-color: rgb(0, 255, 0); position: absolute;">
                    <div style="position:absolute;width:0px;height:0px;"></div>
                </div>
                <audio id="audioPlayer" controls style="margin-top: 20px;"></audio>
                <br>
                <img src="smeter1.png" alt="[scale]">
                <br>
            </div>
        </div>
        <span id="numericalsmeter">&nbsp;&nbsp;-65.8</span> dB;
        peak
        <span id="numericalsmeterpeak">&nbsp;&nbsp;-65.8</span> dB;
        <br>
        <input id="mutecheckbox" title="disable sound" type="checkbox" value="" onclick="setmute(this.checked)">mute
        <input id="squelchcheckbox" title="block noise if no signal" type="checkbox" value=""
            onclick="setsquelch(this.checked)">squelch
        <input id="autonotchcheckbox" title="automatically filter out interfering carrier (beep/whistle)"
            type="checkbox" value="" onclick="setautonotch(this.checked)">autonotch
        <br>
        <span id="volumecontrol" style="white-space:nowrap; width:50%">
            Volume:
            <input type="range" min="-20" max="6" id="volumecontrol2" name="volume" value="0" step="1"
                oninput="soundapplet.setvolume(Math.pow(10,this.value/10.))"
                onchange="soundapplet.setvolume(Math.pow(10,this.value/10.))">
        </span>
        <div id="record_span" style="display: inline;">
            <hr>
            <b>Audio recording: </b>
            <button id="recbutton" onclick="record_click(); return false">start</button>
            <span id="reccontrol"></span>
            <br>
            <div id="recwarning" style="width:300px; display:none; font-size:-1; color:red">Your browser does not seem
                to support downloading the recording; please try a recent version of Firefox, Chrome or Opera.</div>
        </div>
        <hr>
        <b>Signal strength plot:</b>
        <select id="sgraphchoice">
            <option value="0">none</option>
            <option value="1">fast</option>
            <option value="10">slow</option>
        </select>
        <div>
            <canvas id="sgraph" style="width:100%; display:none;"></canvas>
        </div>
    </div>
    <script>
        
        function connectToMQTT() {
            let mqtt = {
    flag: 0,
    host: '192.168.8.76',
    settings: {
        port: 8083,
        http: {
            port: 1883,
            bundle: true,
            static: './'
        },
    },
    username: 'node',
    password: 'node',
    topic: {
        aerocraft_receive: 'center/aerocraft_receive',
    },
}


    var mqttConfig = {
        host: mqtt.host,
        port: mqtt.settings.port,
        clientId: 'client_' + Math.random().toString(16).substr(2, 8), // 生成一个随机的客户端ID
        username: mqtt.username,
        password: mqtt.password,
        keepAliveInterval: 60, // 保持心跳连接的时间间隔
    };
    console.log('开始连接')
    var client = new Paho.MQTT.Client(mqttConfig.host, mqttConfig.port, mqttConfig.clientId);

    // 设置连接认证信息
    client.onConnected = function(reconnect, uri) {
        console.log('已连接到MQTT服务器');
        client.subscribe(mqtt.topic.aerocraft_receive, {
    onSuccess: function() {
      console.log('成功订阅主题');
    },
    onFailure: function(err) {
      console.log('订阅主题失败:', err.errorMessage);
    }
  });
    };
    // 监听消息到达事件
   
client.onMessageArrived = function(message) {
    console.log('收到消息:', message.payloadString);
    var receivedAudioData = message.payloadString;
    var audioPlayer = document.getElementById("audioPlayer");
     // 尝试使用不同的音频格式来播放
     var receivedAudioData = message.payloadString;
    var audioContext = new AudioContext();
    audioContext.decodeAudioData(base64ToArrayBuffer(receivedAudioData), function(buffer) {
        var source = audioContext.createBufferSource();
        source.buffer = buffer;
        source.connect(audioContext.destination);
        source.start(0);
    });
};

function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var len = binaryString.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}


    // 连接到MQTT服务器
    client.connect({
        onSuccess: client.onConnected,
        userName: mqttConfig.username,
        password: mqttConfig.password,
        keepAliveInterval: mqttConfig.keepAliveInterval,
       
    });
}


   
    </script>
    <style>
        .clear {
            clear: both;
        }

        body {
            color: black;
            background-color: #C0C0C0;
        }

        canvas {
            aspect-ratio: auto 1024 / 100;
            overflow-clip-margin: content-box;
            overflow: clip;
        }

        .ctl {
            background: white;
            float: left;
            width: auto;
            margin: 5px;
            border: 2px;
            padding: 5px;
        }

        .hideblind {
            display: inline;
        }
    </style>
</body>

</html>